<template>
  <div class="app-container inden-manage sticky-box">
    <div>
      <avue-form
        :option="option"
        v-model="queryParams"
        ref="searchForm"
        v-show="showSearch"
        @keydown.enter="getList"
      >
        <!-- <template #customerId>
          <el-select
            class="w-full"
            v-model="queryParams.customerId"
            placeholder="请选择客户名称"
            @focus="selectCustomerFn('customerId')"
          >
            <el-option
              v-for="item in customerOption['customerId']"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select> -->
        <!-- <el-select
            v-model="queryParams.customerId"
            placeholder="请选择客户名称"
            class="w-full"
            filterable
            remote
            clearable
            :remote-method="queryCustomer"
            :loading="loadingSelect"
            no-data-text="未查询到客户"
          >
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            >
              <div>
                <span>{{ item.customerName }}</span>
              </div>
            </el-option>
          </el-select>
        </template> -->
        <template #menu-form>
          <el-button icon="Search" type="primary" @click="getList" class="m-l-3"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleEmpty(searchForm)"
            >重置</el-button
          >
          <el-button icon="Filter" type="primary" @click="handleSearch" link
            >高级查询</el-button
          >
        </template>
      </avue-form>

      <el-drawer
        v-model="searchDrawer"
        title="高级检索"
        :show-close="false"
        size="40%"
      >
        <template #header="{ close, titleId, titleClass }">
          <h4 :id="titleId" :class="titleClass">高级检索</h4>
          <el-button
            class="search-drawer-retract"
            icon="ArrowRight"
            type="danger"
            @click="close"
            link
          >
            收起
          </el-button>
        </template>
        <avue-form
          :option="searchOption"
          v-model="queryParams"
          ref="seniorSearchForm"
          @keydown.enter="getList"
        >
          <!-- <template #customerId>
            <el-select
              v-model="queryParams.customerId"
              placeholder="请选择客户名称"
              class="w-full"
              filterable
              remote
              clearable
              :remote-method="queryCustomer"
              :loading="loadingSelect"
              no-data-text="未查询到客户"
            >
              <el-option
                v-for="item in parentOptions"
                :key="item.id"
                :label="item.customerName"
                :value="item.id"
              >
                <div>
                  <span>{{ item.customerName }}</span>
                </div>
              </el-option>
            </el-select>
            <el-select
              class="w-full"
              v-model="queryParams.customerId"
              placeholder="请选择客户名称"
              @focus="selectCustomerFn('customerId')"
            >
              <el-option
                v-for="item in customerOption['customerId']"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
          </template> -->
          <template #projectId>
            <el-select
              v-model="queryParams.projectId"
              placeholder="请选择关联项目"
              class="w-full"
              suffix-icon="Search"
              remote-show-suffix
              :suffix-transition="false"
              filterable
              remote
              clearable
              :remote-method="
                val => queryProjectLimitEnt(val, queryParams.customerId)
              "
              :loading="!projectOptionsLimitEnt"
            >
              <el-option
                v-for="item in projectOptionsLimitEnt"
                :key="item.projectId"
                :label="item.proName"
                :value="item.projectId"
              >
                <div>
                  <span>{{ item.proName }}</span>
                </div>
              </el-option>
            </el-select>
          </template>
          <template #contractId>
            <el-select
              v-model="queryParams.contractId"
              placeholder="请选择关联合同"
              class="w-full"
              suffix-icon="Search"
              remote-show-suffix
              :suffix-transition="false"
              filterable
              remote
              clearable
              :remote-method="
                val => queryContractLimitEnt(val, queryParams.customerId)
              "
              :loading="!contractOptionsLimitEnt"
            >
              <el-option
                v-for="item in contractOptionsLimitEnt"
                :key="item.rcId"
                :label="item.contractName"
                :value="item.rcId"
              >
                <div>
                  <span>{{ item.contractName }}</span>
                </div>
              </el-option>
            </el-select>
          </template>
          <template #menu-form>
            <div class="text-center">
              <el-button icon="Search" type="primary" @click="getList"
                >查询</el-button
              >
              <el-button icon="Refresh" @click="handleEmpty(searchForm)"
                >重置</el-button
              >
            </div>
          </template>
        </avue-form>
      </el-drawer>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="MessageBox"
            plain
            @click="invoicesFn"
            :disabled="disBatch"
            >批量开票</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Connection"
            plain
            @click="invoiceMergeFn"
            :disabled="disBatch"
            >合并开票</el-button
          >
        </el-col>
        <right-toolbar @queryTable="getList" v-model:showSearch="showSearch">
          <el-tooltip
            class="item"
            effect="dark"
            :content="'自定义列表'"
            placement="top"
          >
            <el-button circle icon="Menu" @click="handleTable()" />
          </el-tooltip>
        </right-toolbar>
      </el-row>

      <el-table
        class="sticky-table"
        v-loading="loading"
        :data="tableList"
        row-key="id"
        stripe
        border
        :scrollbar-always-on="true"
        @selection-change="handleSelectionChange"
        :cell-class-name="cellClass"
        @row-dblclick="
          row => {
            goTo('/sales/indent/salesOrderDetails', {
              salesOrderId: row.orderId
            })
          }
        "
      >
        <el-table-column
          type="selection"
          width="40"
          align="center"
          fixed="left"
        />
        <el-table-column
          v-for="(item, index) in tableCol.filter(item => item.show)"
          :key="index"
          v-bind="item"
        >
          <template #default="scope">
            <div v-if="item.tooltip">
              <el-tooltip
                :disabled="!scope.row.invoiceMsg"
                effect="dark"
                :content="item.tooltip(scope.row)"
                placement="top"
              >
                {{ item.tooltipVal(scope.row) }}
              </el-tooltip>
            </div>
            <div v-if="scope.column.label == '状态'">
              <dict-drop :options="order_status" :value="scope.row.ordStatus" />
              <span
                class="text-12px text-#999999"
                v-if="scope.row.approvalStatus"
                >({{ scope.row.approvalStatus }})</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="220"
          fixed="right"
          class-name="small-padding"
        >
          <template #header>
            <div>操作</div>
          </template>
          <template #default="scope">
            <el-button
              plain
              size="small"
              type="primary"
              icon="Postcard"
              :disabled="
                scope.row.ordStatus == '4' ||
                scope.row.synchronousStatus !== '2' ||
                scope.row.approvalStatus !== '审批通过' ||
                scope.row.status == '1' ||
                scope.row.status == '3' ||
                !!scope.row.number
              "
              v-hasPermi="['salesOrder:makeOutInvoice']"
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              @click="invoiceFn(scope.row, scope.$index)"
              >开票</el-button
            ><!-- 
              v-loading="btnLoadingArr[scope.$index]"
 ||
                btnLoadingArr[scope.$index] -->
            <el-button
              plain
              size="small"
              type="primary"
              icon="Sort"
              :disabled="
                scope.row.status == '0' ||
                scope.row.property == 1 ||
                scope.row.status != '1'
              "
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              @click="reversalOrder(scope.row)"
              >冲红</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 人员弹出框下拉框 -->
      <SelectDialog
        :dialog-param="dialogParam"
        @ok="selectDialogData"
        @close="
          val => {
            dialogParam.isDialog = false
          }
        "
      ></SelectDialog>

      <!-- 发票弹出框 -->
      <InvoiceDia
        :dialogParam="invoiceParam"
        @ok="invoicingFn"
        @close="closeInvoiceFn"
      >
        <template
          #bottomBtn
          v-if="invoiceName === '批量开票' && selectArr.length > 0"
        >
          <div class="p-r-5 w-12/24 inline-block flex justify-between">
            <span>
              合同(订单)编号：{{
                selectArr[currentInvoice]?.contractOrderNumber
              }}
            </span>
            <span>
              共 {{ selectArr.length }} 张 / 剩余
              {{ selectArr.length - (currentInvoice + 1) }} 张
            </span>
          </div>
        </template>
      </InvoiceDia>

      <!-- 冲红弹窗 -->
      <InvoiceDialog
        v-model="redInvoiceParam.open"
        :dialogData="redInvoiceParam"
        @getData="redDialogFn"
      />

      <!-- 自定义订单列表弹窗 -->
      <DiaFixTable
        v-model="diaTable.open"
        :dialogParam="diaTable"
        @ok="diaTableFn"
      />

      <!-- 红字开票 -->
      <el-dialog
        :title="invoicingDialog.title"
        v-model="invoicingDialog.open"
        width="40%"
        :close-on-click-modal="false"
      >
        <el-form
          ref="invoicingRef"
          :model="invoicingData"
          :rules="invoicingRules"
          label-width="120px"
          status-icon
        >
          <el-row>
            <el-col :span="24" class="p-t-5">
              <el-form-item label="冲红原因" prop="redReason">
                <el-select
                  class="w-full"
                  v-model="invoicingData.redReason"
                  placeholder="请选择冲红原因"
                >
                  <el-option
                    v-for="item in red_reason"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="invoicingDialog.open = false">取 消</el-button>
            <el-button
              type="primary"
              @click="handleInvoicing"
              v-loading="invoicingLoading"
              >确定</el-button
            >
          </span></template
        >
      </el-dialog>
    </div>
  </div>
</template>
<script setup name="OrderInvoice">
import { reactive, toRefs, ref, toRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  order_status, //订单状态
  order_biz_type, //业务类型
  order_source, //订单来源
  order_invoice_status, //发票状态
  order_synchronous_status, //同步状态
  invoice_manage_type, //发票类型
  crm_status, //crm同步状态
  nuonuo_status, //诺诺同步状态
  companyOption, //所属公司
  businessTypeOption, //业务类型树
  projectOptionsLimitEnt, //项目数据
  queryProjectLimitEnt, //检索项目
  contractOptionsLimitEnt, //合同数据
  queryContractLimitEnt, //检索合同数据
  ORDERINVOICETABLE as INITTABLE //订单列表配置
} from '@/hooks/dict/order'
import {
  listBilling,
  mergerOrder,
  makeOutInvoice,
  redMakeOutInvoice
} from '@/api/indentManage/indent'
import { treeselect } from '@/api/rsgl/zzjg'
import { getPricipalId, initTable } from '@/utils/commo'
import InvoiceDia from './modules/invoiceDia'
import useCommonStore from '@/store/modules/common'
import { format, startOfMonth, endOfMonth } from 'date-fns'
import { maxDecimals } from '@/utils/validate'
import useUserStore from '@/store/modules/user'

const commonStore = useCommonStore()

const btnLoadingArr = ref([])

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const now = new Date()
const { red_reason } = proxy.useDict(
  'red_reason' //冲红原因
)
console.log('red_reason==>', red_reason)
const userOption = ref({ transactionId: [] })
const deptIdOption = ref([])
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    number: undefined,
    status: undefined,
    receiptsDates: [
      format(startOfMonth(now), 'yyyy-MM-dd'),
      format(endOfMonth(now), 'yyyy-MM-dd')
    ],
    bizType: undefined,
    source: undefined,
    customerId: undefined,
    price: undefined,
    projectId: undefined,
    invoiceStatus: undefined,
    contractId: undefined,
    deptId: userStore.userInfo.orgId,
    businessType: undefined
  },
  ids: [],
  selectArr: [],
  total: 0,
  option: {
    labelWidth: '10',
    menuSpan: 7,
    submitBtn: false,
    menuPosition: 'left',
    // gutter: 30,
    emptyBtn: false,
    column: [
      {
        prop: 'contractOrderNumber',
        span: 3,
        placeholder: '订单号',
        type: 'input'
      },
      {
        // label: '性别',
        span: 3,
        prop: 'status',
        placeholder: '状态',
        type: 'select',
        dicData: order_status
      },
      {
        prop: 'receiptsDates',
        type: 'daterange',
        span: 6,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '单据开始时间',
        endPlaceholder: '单据结束时间'
      },
      {
        prop: 'deptId',
        span: 3,
        placeholder: '所属公司',
        type: 'tree',
        defaultExpandAll: true,
        disabled: userStore.userInfo.orgId != 484,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption
      },
      {
        span: 4,
        prop: 'customerName',
        placeholder: '客户名称',
        type: 'input'
      },
      {
        span: 4,
        prop: 'customerCreditCode',
        placeholder: '税号',
        type: 'input'
      },
      {
        prop: '_transactionId',
        span: 3,
        placeholder: '所属人员',
        type: 'select',
        clearable: false,
        props: {
          value: 'uuid'
        },
        popperClass: 'className',
        dicData: computed(() => {
          return userOption.value['transactionId']
        }),
        multiple: false,
        click: ({ value, column }) => {
          dialogParam.value.type = 'transactionId'
          dialogParam.value.title = '请选择人员'
          dialogParam.value.isDialog = true
          dialogParam.value.multiple = false
          dialogParam.value.nodeKey = 'uuid'
          dialogParam.value.apiParams = { deptId: 100 }
          dialogParam.value.defaultCheckedKeys = [
            queryParams.value._transactionId
          ]
          dialogParam.value.dataType = 'person'
        }
      },
      {
        span: 3,
        prop: 'invoiceStatus',
        placeholder: '发票状态',
        type: 'select',
        dicData: order_invoice_status
      },
      {
        span: 3,
        prop: 'synchronousStatus',
        placeholder: 'A8同步状态',
        type: 'select',
        dicData: order_synchronous_status
      },
      {
        prop: 'approvalTime',
        type: 'daterange',
        span: 5,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '最新审核开始时间',
        endPlaceholder: '最新审核结束时间'
      },
      {
        span: 3,
        prop: 'productName',
        placeholder: '产品名称',
        type: 'input'
      }
    ]
  },
  searchOption: {
    labelWidth: '120',
    submitBtn: false,
    emptyBtn: false,
    menuPosition: 'left',
    column: [
      {
        label: '订单查询',
        prop: 'number',
        span: 12,
        placeholder: '订单号',
        type: 'input'
      },
      {
        label: '状态',
        span: 12,
        prop: 'status',
        placeholder: '状态',
        type: 'select',
        dicData: order_status
      },
      {
        label: '单据时间',
        prop: 'receiptsDates',
        type: 'daterange',
        span: 12,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '单据开始时间',
        endPlaceholder: '单据结束时间'
      },
      {
        label: '业务类型',
        span: 12,
        prop: 'bizType',
        placeholder: '业务类型',
        type: 'select',
        dicData: order_biz_type
      },
      // {
      //   label: '付款时间',
      //   prop: 'payDates',
      //   type: 'daterange',
      //   span: 12,
      //   format: 'YYYY-MM-DD',
      //   valueFormat: 'YYYY-MM-DD',
      //   startPlaceholder: '付款开始时间',
      //   endPlaceholder: '付款结束时间'
      // },
      {
        label: '订单来源',
        span: 12,
        prop: 'source',
        placeholder: '订单来源',
        type: 'select',
        dicData: order_source
      },
      {
        label: '客户名称',
        span: 12,
        prop: 'customerName',
        placeholder: '客户名称'
      },
      {
        label: '订单金额',
        span: 12,
        prop: 'price',
        placeholder: '订单金额',
        type: 'number',
        controls: false,
        rules: [
          {
            validator: (rule, value, callback) => {
              maxDecimals(rule, value, callback, 6)
            }
          }
        ]
        // dicData: order_price
      },
      {
        label: '关联项目',
        span: 12,
        prop: 'projectId',
        placeholder: '关联项目'
      },
      {
        label: '发票状态',
        span: 12,
        prop: 'invoiceStatus',
        placeholder: '发票状态',
        type: 'radio',
        dicData: order_invoice_status
      },
      {
        label: '关联合同',
        span: 12,
        prop: 'contractId',
        placeholder: '关联合同'
      },

      {
        label: '所属公司',
        prop: 'deptId',
        span: 12,
        placeholder: '所属公司',
        defaultExpandAll: true,
        type: 'tree',
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption,
        change: val => {
          queryParams.value.deptId = val.value
          getDeptTree()
        }
      },
      {
        label: '所属部门',
        prop: 'transactionDept',
        span: 12,
        placeholder: '所属部门',
        type: 'tree',
        defaultExpandAll: true,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: deptIdOption
      },
      {
        label: '业务板块',
        span: 12,
        prop: 'businessType',
        placeholder: '业务板块',
        type: 'tree',
        dicData: businessTypeOption
      },
      {
        label: '发票类型',
        span: 12,
        prop: 'invoiceType',
        placeholder: '发票类型',
        type: 'tree',
        dicData: invoice_manage_type
      },
      {
        label: '所属人员',
        prop: '_transactionId',
        span: 12,
        placeholder: '所属人员',
        type: 'select',
        clearable: false,
        props: {
          value: 'uuid'
        },
        popperClass: 'className',
        dicData: computed(() => {
          return userOption.value['transactionId']
        }),
        multiple: false,
        click: ({ value, column }) => {
          dialogParam.value.type = 'transactionId'
          dialogParam.value.title = '请选择人员'
          dialogParam.value.isDialog = true
          dialogParam.value.multiple = false
          dialogParam.value.nodeKey = 'uuid'
          dialogParam.value.apiParams = { deptId: 100 }
          dialogParam.value.defaultCheckedKeys = [
            queryParams.value._transactionId
          ]
          dialogParam.value.dataType = 'person'
        }
      },
      {
        label: 'crm同步状态',
        span: 12,
        prop: 'crmStatus',
        placeholder: 'crm同步状态',
        type: 'tree',
        dicData: crm_status
      },
      {
        label: '诺诺同步状态',
        span: 12,
        prop: 'nuonuoStatus',
        placeholder: '诺诺同步状态',
        type: 'tree',
        dicData: nuonuo_status
      },
      {
        label: '爱企服同步状态',
        span: 12,
        prop: 'aisinoStatus',
        placeholder: '爱企服同步状态',
        type: 'tree',
        dicData: nuonuo_status
      },
      {
        label: '订单查询',
        prop: 'numberText',
        span: 24,
        placeholder: '请输入订单编号，回车空格，,分割例如：123,456,789',
        type: 'textarea',
        autosize: true
        // minRows: 3
      }
    ]
  },
  showSearch: true,
  searchDrawer: false /* 高级检索框 */,
  disBatch: true /* 批量开票 */,
  loading: false,
  tableList: [],
  dialogParam: {}
})
const {
  queryParams,
  ids,
  selectArr,
  total,
  option,
  searchOption,
  showSearch,
  searchDrawer,
  disBatch,
  loading,
  tableList,
  dialogParam
} = toRefs(data)
watch(
  [() => route.query.salesOrderData],
  async () => {
    if (route.query.salesOrderData) {
      queryParams.value = JSON.parse(route.query.salesOrderData)
      getList()
    }
  },
  {
    immediate: true
  }
)

const tableCol = ref(INITTABLE)
// 自定义列表弹窗参数
const diaTable = ref({
  open: false,
  tableName: 'orderInvoiceTable',
  tableCol: tableCol.value,
  initCol: INITTABLE
})

// 自定义列表
const handleTable = () => {
  diaTable.value.open = true
  diaTable.value.tableCol = tableCol.value
}
const cellClass = ({ row, column }) => {
  // console.log('row', row)
  // console.log('column', column)
}
// 获取列表配置
const diaTableFn = value => {
  tableCol.value = value
}

// 初始化
async function init() {
  // 初始化列表配置
  // if (userStore.userInfo.listDisaplayObj?.orderInvoiceTable) {
  //   let _tableCol = JSON.parse(
  //     userStore.userInfo.listDisaplayObj['orderInvoiceTable']
  //   )
  //   // 过滤出本地新增的列
  //   let initItmes = INITTABLE.filter(
  //     item => !_tableCol.some(item1 => item1.prop == item.prop)
  //   )
  //   tableCol.value = []
  //   _tableCol.forEach(item => {
  //     let newItem = {}
  //     for (const e of INITTABLE) {
  //       if (e.prop == item.prop) {
  //         newItem = { ...e, ...item, label: e.label }
  //         tableCol.value.push(newItem)
  //         break
  //       }
  //     }
  //   })
  //   tableCol.value = [...tableCol.value, ...initItmes]
  // }
  tableCol.value = initTable(diaTable.value.tableName, INITTABLE)
  // console.log('tableCol.value==>', tableCol.value)
  // 归属部门
  getList()
}
// 获取部门树
const getDeptTree = () => {
  if (!queryParams.value.deptId) return
  queryParams.value.transactionDept = ''
  let data = { deptId: queryParams.value.deptId }
  treeselect(data).then(res => {
    deptIdOption.value = res.data
  })
}
getDeptTree()
// 重置
function handleEmpty(formEl) {
  console.log('queryParams.value1==>', toRaw(queryParams.value))
  proxy.resetForm('searchForm')
  proxy.resetForm('seniorSearchForm')
  // proxy.$refs.searchForm.resetForm()
  getList()
}
// 高级检索
function handleSearch() {
  searchDrawer.value = true
}

// 获取数据列表
function getList() {
  loading.value = true
  // 所属人员
  queryParams.value.transactionId = getPricipalId(
    userOption.value['transactionId'],
    queryParams.value._transactionId || ''
  ).toString()
  console.log('queryParams.value2==>', queryParams.value)
  listBilling(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
    console.log(' tableList.value==>', tableList.value)
    if (res.msg != '查询成功') {
      proxy.$message.error(res.msg)
    }
  })
  console.log('获取数据')
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disBatch.value =
    !selection.length ||
    selection.some(
      item =>
        item.ordStatus == '4' ||
        item.synchronousStatus !== '2' ||
        item.approvalStatus !== '审批通过' ||
        item.status == '1' ||
        item.status == '3' ||
        item.number ||
        item.property !== selection[0].property
    )
}
// 双击行
function dbclickRow(row, column, event) {
  goTo('/sales/indent/salesOrderDetails', {
    salesOrderId: row.id
  })
}

function goTo(url, data) {
  router.push({ path: url, query: data })
}

/* 人员确认 */
const selectDialogData = val => {
  switch (val.type) {
    case 'transactionId':
      userOption.value.transactionId = val.selectData
      // queryOption.value.column[2].dicData = val.selectData
      queryParams.value._transactionId = val.defaultCheckedKeys.toString()
      break
  }
}

// 发票信息弹窗参数
const invoiceParam = ref({
  open: false
})
const redInvoiceParam = ref({
  open: false
})

// 冲红表单
const invoicingData = ref({})
const invoicingRules = ref({
  redReason: [
    {
      required: true,
      message: '请选择冲红原因',
      trigger: 'change'
    }
  ]
})
// 开票弹窗
const invoicingDialog = ref({
  open: false,
  title: '红字开票'
})
// 蓝字开票名称
const invoiceName = ref('')
const rowIndex = ref()
// 点击开票按钮
const invoiceFn = async (row, index) => {
  rowIndex.value = index
  if (row.property == '0') {
    //订单蓝字
    // let res = await getSalesOrder(row.id)
    // if (res.code !== 200) return
    invoiceName.value = '开票'
    invoiceParam.value.open = true
    invoiceParam.value.formData = row //res.data
  } else if (row.property == '1') {
    //订单红字字
    invoicingDialog.value.open = true
    invoicingData.value.orderId = row.orderId
    proxy.resetForm('invoicingRef')
  }
}
// 批量开票当前票据
const currentInvoice = ref(0)
// 点击批量开票按钮
const invoicesFn = async () => {
  if (selectArr.value[0].property == '0') {
    currentInvoice.value = 0
    //订单蓝字
    invoiceName.value = '批量开票'
    invoiceParam.value.open = true
    invoiceParam.value.btnLoading = false
    invoiceParam.value.formData = selectArr.value[currentInvoice.value]
  } else {
    proxy.$modal.msgError('请选择蓝字订单')
  }
}
// 点击合并开票按钮
const invoiceMergeFn = async () => {
  if (selectArr.value[0].property == '0') {
    let data = { invoiceIdList: ids.value }
    let res = await mergerOrder(data)
    if (res.code !== 200) return
    //订单蓝字
    invoiceName.value = '合并开票'
    invoiceParam.value.open = true
    invoiceParam.value.btnLoading = false
    invoiceParam.value.formData = res.data
  } else {
    proxy.$modal.msgError('请选择蓝字订单')
  }
}

// 确定红字开票
const invoicingLoading = ref(false)
const handleInvoicing = () => {
  invoicingLoading.value = true
  proxy.$refs.invoicingRef.validate(async (valid, msg) => {
    if (valid) {
      try {
        let res = await redMakeOutInvoice(invoicingData.value)
        if (res.code == 200) {
          invoicingDialog.value.open = false
          proxy.$modal.msgSuccess('提交成功')
          getList()
        }
        invoicingLoading.value = false
      } catch (error) {
        invoicingLoading.value = false
      }
    } else {
      invoicingLoading.value = false
    }
  })
}

// 蓝字开票
const invoicingFn = async val => {
  if (invoiceName.value === '批量开票') {
    try {
      invoiceParam.value.btnLoading = true
      let resOutInvoice = await makeOutInvoice(val)
      if (resOutInvoice.code !== 200) return
      invoiceParam.value.btnLoading = false
      proxy.$modal.msgSuccess('提交成功')
      currentInvoice.value++
      invoiceParam.value.formData = selectArr.value[currentInvoice.value]
      // invoiceParam.value.open = false
    } catch (error) {
      if (selectArr.value.length - (currentInvoice.value + 1) === 0) {
        invoiceParam.value.open = false
        return
      }
      proxy
        .$confirm('开票失败，是否继续开票', '提示', {
          confirmButtonText: '开下一张票',
          cancelButtonText: '继续开当前票',
          type: 'warning'
        })
        .then(() => {
          invoiceParam.value.btnLoading = false
          currentInvoice.value++
          invoiceParam.value.formData = selectArr.value[currentInvoice.value]
        })
        .catch(() => {
          invoiceParam.value.btnLoading = false
        })
    }
    if (selectArr.value.length - (currentInvoice.value + 1) < 0) {
      invoiceParam.value.open = false
      return
    }
  } /*  else if (invoiceName.value === '开票') {
    invoiceParam.value.btnLoading = true
    // btnLoadingArr.value[rowIndex.value] = true
    // console.log('开票val===>', val)
    try {
      let resOutInvoice = await makeOutInvoice(val)
      if (resOutInvoice.code !== 200) return
      proxy.$modal.msgSuccess('提交成功')
      invoiceParam.value.open = false
      // btnLoadingArr.value[rowIndex.value] = false
      invoiceParam.value.btnLoading = false
      getList()
    } catch (error) {
      invoiceParam.value.open = false
      // btnLoadingArr.value[rowIndex.value] = false
      invoiceParam.value.btnLoading = false
    }
  } */ else if (
    invoiceName.value === '合并开票' ||
    invoiceName.value === '开票'
  ) {
    invoiceParam.value.btnLoading = true
    // console.log('开票val===>', val)
    try {
      let resOutInvoice = await makeOutInvoice(val)
      if (resOutInvoice.code !== 200) return
      proxy.$modal.msgSuccess('提交成功')
      invoiceParam.value.open = false
      invoiceParam.value.btnLoading = false
      getList()
    } catch (error) {
      invoiceParam.value.open = false
      invoiceParam.value.btnLoading = false
    }
  }
}
const closeInvoiceFn = async () => {
  invoiceParam.value.open = false
  getList()
}
// 点击冲红
async function reversalOrder(row) {
  //订单红字
  redInvoiceParam.value.open = true
  redInvoiceParam.value.isSelection = false
  redInvoiceParam.value.dialogType = '冲红'
  redInvoiceParam.value.query = {
    orderId: row.orderId,
    openStatus: '1'
  }
}
// 冲红开票弹窗时
const redDialogFn = val => {
  console.log('冲红==>', val)
  getList()
}

init()
</script>
<style scoped lang="scss">
@import '@/assets/styles/myStyle.scss';
</style>
<style scoped lang="scss">
.search-drawer-retract {
  color: #999999;
}
</style>
